import {
  Box3Get,
  setUserAuth,
  setUserData,
  apiType,
  nPost,
} from "@ap/util/request";
import * as vscode from "vscode";
import { userCenterToolItems } from "@ap/command";
import {
  showErrorMessage,
  showInformationMessage,
  loginNullMsg,
  loginTokenMsg,
} from "@ap/util/vscode/message";
import {
  ConfigurationItem,
  ConfigurationKey,
  setInsConfig,
} from "@ap/util/vscode/setInsConfig";
import { UserDataRootObject } from "@ap/types/config";
import { CreateStatusBar } from "@ap/init";
import { CommandId } from "@ap/command";
/**
 * 请求选项配置，定义了获取内容列表的API请求参数。
 */
const requestOptions = {
  url: "auth/user",
};

let isLogin = false;
/**
 * 异步获取用户数据。
 * @returns 返回承诺，解析为数据项数组。
 */
export async function login(isShowInput: boolean = true) {
  if (isLogin) {
    return;
  }
  isLogin = true;

  try {
    const accountToken = vscode.workspace
      .getConfiguration(ConfigurationItem.USER_CENTER_TOOL)
      .get<string>(ConfigurationKey.ACCOUNT_TOKEN);
    const ua = vscode.workspace
      .getConfiguration(ConfigurationItem.USER_CENTER_TOOL)
      .get<string>(ConfigurationKey.USER_AGNET);
    if (!accountToken || !ua) {
      isLogin = false;
      return;
    }
    const dataJson = isValidJson(accountToken);
    if (dataJson) {
      setInsConfig(
        ConfigurationItem.USER_CENTER_TOOL,
        ConfigurationKey.ACCOUNT_TOKEN,
        dataJson,
      );
      setUserAuth(dataJson, ua);
    } else {
      setUserAuth(accountToken, ua);
    }
    /**
     * 发送请求并等待响应。
     */
    const response = await Box3Get(requestOptions, "账号授权");
    /**
     * 检查响应是否成功，如果不成功则返回错误消息。
     */
    if (!response || response.code !== 200) {
      const errorMsg = isShowInput
        ? `神岛账号登录失败：${response?.msg}，当前环境：${apiType}`
        : `ArenaPro：账号Token已失效，请尝试重新登录`;
      setInsConfig(
        ConfigurationItem.USER_CENTER_TOOL,
        ConfigurationKey.ACCOUNT_TOKEN,
        "",
      );
      setInsConfig(
        ConfigurationItem.USER_CENTER_TOOL,
        ConfigurationKey.USER_AGNET,
        "",
      );
      if (await loginNullMsg(errorMsg)) {
        openLoginSetting();
      }
      updateUIWithResponse();
      isLogin = false;
      return response?.msg as string;
    }
    setUserData(response as UserDataRootObject);
    updateUIWithResponse(response);
    isLogin = false;
    return response;
  } catch (error) {
    showErrorMessage(error);
    updateUIWithResponse();
    isLogin = false;
    return;
  }
}

/**
 * 退出登录，删除本地用户信息。
 */
export async function logout() {
  try {
    setUserData();
    updateUIWithResponse();
  } catch (error) {
    showErrorMessage(error);
  }
}

export function openLoginSetting() {
  vscode.commands.executeCommand(
    CommandId.ap_openSettings,
    "@ext:box3lab.box3arenapro " + ConfigurationItem.USER_CENTER_TOOL,
  );
}
/**
 * 根据响应数据更新用户中心的UI展示。
 * @param response 可选参数，包含用户信息的响应对象。
 */
function updateUIWithResponse(response?: Record<string, any>): void {
  vscode.commands.executeCommand(CommandId.map_treeDataMapRefresh);
  if (response) {
    // 如果response存在，则设置用户中心工具的颜色为成功状态的颜色，并更新标签为用户的昵称和用户ID。
    CreateStatusBar.userCenterToolObj.color =
      CreateStatusBar.STATUS_SUCCESS_COLOR;
    CreateStatusBar.userCenterToolObj.tooltip = `你好，${response.data.nickname}(${response.data.userId})`;
    userCenterToolItems[0].label = `$(accounts-view-bar-icon) 账号：${response.data.nickname}(${response.data.userId})`;
  } else {
    // 如果response不存在，则设置用户中心工具的颜色为默认状态的颜色，并更新标签为授权提示信息。
    CreateStatusBar.userCenterToolObj.color = CreateStatusBar.STATUS_BAR_COLOR;
    CreateStatusBar.userCenterToolObj.tooltip = ``;
    userCenterToolItems[0].label = `$(accounts-view-bar-icon) 登录神岛账号`;
  }
}

function isValidJson(jsonString: string): false | undefined | string {
  try {
    return JSON.parse(jsonString).data.token;
  } catch (error) {
    return false;
  }
}

export async function loginInput() {
  loginTokenMsg(
    "获取神岛账号Token方法请打开以下网址：https://code-api-pc.dao3.fun/auth/user",
    "https://code-api-pc.dao3.fun/auth/user",
  );
  const loginToken = await vscode.window.showInputBox({
    title: "神岛账号登录",
    prompt: `请输入神岛账号Token。`,
    ignoreFocusOut: true,
  });
  loginTokenMsg(
    "获取浏览器用户代理(User-Agent)方法请打开以下网址：https://passer-by.com/browser",
    "https://passer-by.com/browser",
  );
  const loginUA = await vscode.window.showInputBox({
    title: "神岛账号登录",
    prompt: `请输入浏览器用户代理(User-Agent)。`,
    ignoreFocusOut: true,
  });

  if (!loginToken || !loginUA) {
    vscode.commands.executeCommand(CommandId.userCenterTool_setting);
    showInformationMessage(
      "没有输入神岛账号Token或用户代理，现已跳转至神岛账号设置界面",
    );
    return "没有输入神岛账号Token或用户代理，现已跳转至神岛账号设置界面";
  }

  isLogin = true;
  await setInsConfig(
    ConfigurationItem.USER_CENTER_TOOL,
    ConfigurationKey.USER_AGNET,
    loginUA,
  );
  const dataJson = isValidJson(loginToken);
  if (dataJson) {
    await setInsConfig(
      ConfigurationItem.USER_CENTER_TOOL,
      ConfigurationKey.ACCOUNT_TOKEN,
      dataJson,
    );
    setUserAuth(dataJson, loginUA);
  } else {
    setUserAuth(loginToken, loginUA);
  }

  /**
   * 发送请求并等待响应。
   */
  const response = await Box3Get(requestOptions, "账号授权");
  /**
   * 检查响应是否成功，如果不成功则返回错误消息。
   */
  if (!response || response.code !== 200) {
    const errorMsg = `神岛账号登录失败：${response?.msg}，当前环境：${apiType}`;

    updateUIWithResponse();
    isLogin = false;
    return errorMsg as string;
  }
  setUserData(response as UserDataRootObject);
  updateUIWithResponse(response);
  isLogin = false;
  return response;
}
